package com.ysdz.tibetan.tibetanmini.security.provider;

import com.ysdz.tibetan.tibetanmini.security.beans.ConsumerDetails;
import com.ysdz.tibetan.tibetanmini.security.service.UserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author zhangyu
 * @description 用户登录验证
 */
@Component
public class UserAuthenticationProvider implements AuthenticationProvider  {

    @Autowired
    private UserDetailServiceImpl userDetailServiceImpl;

    @Value("${wx.applet.appid}")
    private static String wxPassword;

    /**
     * 身份验证
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取用户名
        String username = (String) authentication.getPrincipal();
        // 获取密码
        String password = (String) authentication.getCredentials();

        ConsumerDetails consumerDetails = (ConsumerDetails) userDetailServiceImpl.loadUserByUsername(username);

        if (consumerDetails == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        if (!new BCryptPasswordEncoder().matches(password, consumerDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        // 通过判断密码区分登录角色,微信角色登录密码为空,管理员密码则不为空
        if (Objects.equals("", password)) {
            if (!new BCryptPasswordEncoder().matches(password, consumerDetails.getPassword())) {
                throw new BadCredentialsException("用户名或密码错误");
            }
            return new UsernamePasswordAuthenticationToken(consumerDetails, password, consumerDetails.getAuthorities());
        }
        return new UsernamePasswordAuthenticationToken(consumerDetails, wxPassword, consumerDetails.getAuthorities());
    }

    /**
     * 支持指定的身份验证
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}
